package com.wjy.sfhcore.ui.fragment;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewStub;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.wjy.sfhcore.BuildConfig;
import com.wjy.sfhcore.CoreApplication;
import com.wjy.sfhcore.R;
import com.wjy.sfhcore.itf.IntentListener;
import com.wjy.sfhcore.itf.OnNetStateChanged;
import com.wjy.sfhcore.itf.impl.FragmentIntentFactory;
import com.wjy.sfhcore.ui.activity.CoreActivity;
import com.wjy.sfhcore.ui.widget.MyProgressBar;
import com.wjy.sfhcore.util.ImagePipelineConfigFactory;
import com.wjy.sfhcore.util.ResourceIDHelp;
import com.wjy.sfhcore.util.Tools;
import com.wjy.sfhcore.util.UIUtils;

import java.lang.reflect.Field;


/**
 * Created by wangjingyuan on 15/7/31.
 * 核心Fragment
 */
public abstract class CoreFragment extends Fragment implements OnNetStateChanged {
    private boolean DEBUG = BuildConfig.DEBUG;
    /**
     * 模态
     */
    public MyProgressBar mProgressBar;

    private IntentListener intentFactory;
    protected CoreActivity baseActivity;
    public final String TAG = getClass().getSimpleName();
    public View viewNoNet, viewLoadFail, viewLoading, viewContainer;

    public enum LoadResult {
        LOAD_SUCCESS,
        LOAD_FAIL,
        NO_NET,
        LOADING
    }

    protected LoadResult loadResult = LoadResult.LOAD_SUCCESS;

    public Toolbar mToolBar;
    /**
     * Toolbar title实例
     */
    public TextView mTitle;
    /**
     * 顶导容器
     * 不使用Toolbar的情况下将自己的title放入容器中
     */
    public ViewStub mTitleContainerStub;
    public FrameLayout mTitleContainer;
    private TextView net_tips;

    @Override
    public void onAttach(Activity activity) {
        baseActivity = (CoreActivity) activity;
        if (DEBUG)
            System.out.println(((Object) this).getClass().getSimpleName() + "开始onAttach");
        super.onAttach(activity);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        Fresco.initialize(baseActivity, ImagePipelineConfigFactory.getImagePipelineConfig(baseActivity));
        if (DEBUG)
            System.out.println(((Object) this).getClass().getSimpleName() + "开始onCreate");
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);    //打开fragment的menu功能
        intentFactory = new FragmentIntentFactory(this);
        mProgressBar = new MyProgressBar(getActivity());
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (isInitToolBar()) {
            initToolbar(view);
        }
        initViews(view);
        changeViewState(loadResult);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                initBackButton();
                return true;
            default:
                menuListener(item);
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Bundle bundle = null;
        if (data != null) {
            bundle = data.getBundleExtra(CoreActivity.PARAM_INTENT);
            if (bundle == null) {
                bundle = data.getExtras();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
        onActivityResult(requestCode, resultCode, bundle);
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        if (DEBUG)
            System.out.println(((Object) this).getClass().getSimpleName()
                    + "开始onActivityCreated");
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onStart() {
        if (DEBUG)
            System.out.println(((Object) this).getClass().getSimpleName() + "开始onStart");
        super.onStart();
    }

    @Override
    public void onResume() {
        if (DEBUG)
            System.out.println(((Object) this).getClass().getSimpleName() + "开始onResume");
        super.onResume();
    }

    @Override
    public void onPause() {
        if (DEBUG)
            System.out.println(((Object) this).getClass().getSimpleName() + "开始onPause");
        super.onPause();
    }

    @Override
    public void onDestroyView() {
        if (isInitToolBar()) {
            CoreApplication.getInstance().unRegisterNetStateWatcher(this);
        }
        if (DEBUG)
            System.out.println(((Object) this).getClass().getSimpleName()
                    + "开始onDestroyView");
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        Fresco.shutDown();
        if (DEBUG)
            System.out.println(((Object) this).getClass().getSimpleName() + "开始onDestroy");
        super.onDestroy();
    }

    @Override
    public void onDetach() {
        if (DEBUG)
            System.out.println(((Object) this).getClass().getSimpleName() + "开始onDetach");
        super.onDetach();
    }

    /**
     * 往容器里面添加fragment
     *
     * @param fragment
     */
    public void addFragment(Fragment fragment) {
        intentFactory.addFragment(fragment);
    }

    /**
     * 替换容器里面的fragment
     *
     * @param newFragment
     */
    public void replaceFragment(Fragment newFragment) {
        intentFactory.replaceFragment(newFragment);
    }

    /**
     * fragment替换
     *
     * @param newFragment    碎片
     * @param addToBackStack 是否保存堆栈信息
     */
    public void replaceFragment(Fragment newFragment, boolean addToBackStack) {
        intentFactory.replaceFragment(newFragment, addToBackStack);
    }

    /**
     * fragment替换
     *
     * @param contentID      容器ID
     * @param newFragment    碎片
     * @param addToBackStack 是否保存堆栈信息
     */
    public void replaceFragment(int contentID, Fragment newFragment,
                                boolean addToBackStack) {
        intentFactory.replaceFragment(contentID, newFragment, addToBackStack);
    }

    /**
     * 单纯的页面跳转
     *
     * @param cls 跳转的页面
     */
    public void goToOthers(Class<?> cls) {
        intentFactory.goToOthers(cls);
    }

    /**
     * 页面跳转并关闭当前页面
     *
     * @param cls 跳转的页面
     */
    public void goToOthersF(Class<?> cls) {
        intentFactory.goToOthersF(cls);
    }

    /**
     * 带参数的页面跳转
     *
     * @param cls    跳转的页面
     * @param bundle 参数
     */
    public void goToOthers(Class<?> cls, Bundle bundle) {
        intentFactory.goToOthers(cls, bundle);
    }

    /**
     * 带参数的页面跳转并关闭当前页面
     *
     * @param cls    跳转的页面
     * @param bundle 参数
     */
    public void goToOthersF(Class<?> cls, Bundle bundle) {
        intentFactory.goToOthersF(cls, bundle);
    }

    /**
     * 带回调的页面跳转
     *
     * @param cls         跳转的页面
     * @param bundle      参数
     * @param requestCode 请求码
     */
    public void goToOthersForResult(Class<?> cls, Bundle bundle, int requestCode) {
        intentFactory.goToOthersForResult(cls, bundle, requestCode);
    }

    /**
     * 设置回调
     *
     * @param cls        回调的页面
     * @param bundle     参数
     * @param resultCode 返回码
     */
    public void backForResult(Class<?> cls, Bundle bundle, int resultCode) {
        intentFactory.backForResult(cls, bundle, resultCode);
    }

    /**
     * 页面回调函数
     *
     * @param requestCode 请求码
     * @param resultCode  返回码
     * @param data        数据
     */
    protected void onActivityResult(int requestCode, int resultCode, Bundle data) {

    }

    protected void changeViewState(LoadResult loadResult) {
        this.loadResult = loadResult;
        switch (loadResult) {
            case LOAD_SUCCESS:
                viewNoNet.setVisibility(View.GONE);
                viewLoading.setVisibility(View.GONE);
                viewLoadFail.setVisibility(View.GONE);
                viewContainer.setVisibility(View.VISIBLE);
                break;
            case LOAD_FAIL:
                viewNoNet.setVisibility(View.GONE);
                viewLoading.setVisibility(View.GONE);
                viewLoadFail.setVisibility(View.VISIBLE);
                viewContainer.setVisibility(View.GONE);
                break;
            case LOADING:
                viewNoNet.setVisibility(View.GONE);
                viewLoading.setVisibility(View.VISIBLE);
                viewLoadFail.setVisibility(View.GONE);
                viewContainer.setVisibility(View.GONE);
                break;
            case NO_NET:
                viewNoNet.setVisibility(View.VISIBLE);
                viewLoading.setVisibility(View.GONE);
                viewLoadFail.setVisibility(View.GONE);
                viewContainer.setVisibility(View.GONE);
                break;
        }
    }

    public void initViews(View view) {
        viewLoadFail = view.findViewById(R.id.view_load_fail);
        viewLoading = view.findViewById(R.id.ll_loading);
        viewContainer = view.findViewById(R.id.container);
        viewNoNet = view.findViewById(R.id.view_no_net);
    }

    /**
     * 处理toolbar菜单
     *
     * @param item
     */
    public abstract void menuListener(MenuItem item);

    /**
     * 处理toolbar返回键
     */
    public abstract void initBackButton();

    /**
     * 初始化顶部导航
     */
    private void initToolbar(View view) {
        if (isUseToolBar()) {
            mToolBar = (Toolbar) view.findViewById(R.id.toolBar);
            baseActivity.setSupportActionBar(mToolBar);
            if (mToolBar != null) {
                if (isShowBackButton()) {
                    try {
                        mToolBar.setNavigationIcon(ResourceIDHelp.getDrawableId(
                                UIUtils.getString(R.string.navigation_back_icon)));
                    } catch (Resources.NotFoundException e) {
                        throw new RuntimeException(UIUtils.getString(R.string.error_not_found_back_icon));
                    }
                }
                try {
                    mToolBar.setBackgroundColor(UIUtils.getColor(
                            ResourceIDHelp.getColorId(UIUtils.getString(R.string.toolBar_bg_color))));
                } catch (Resources.NotFoundException e) {
                    throw new RuntimeException(UIUtils.getString(R.string.error_not_found_tooBar_bg_color));
                }
                try {
                    Class cls = mToolBar.getClass();
                    Field field = cls.getDeclaredField("mTitleTextView");
                    field.setAccessible(true);
                    mTitle = (TextView) field.get(mToolBar);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            mToolBar = (Toolbar) view.findViewById(R.id.toolBar);
            mToolBar.setVisibility(View.GONE);
            mTitleContainerStub = (ViewStub) view.findViewById(R.id.toolBarContainer);
            mTitleContainerStub.inflate();
            mTitleContainer = (FrameLayout) view.findViewById(R.id.toolBarContainer);
        }
        net_tips = (TextView) view.findViewById(R.id.no_net_tips);
        if (Tools.isConnectNet(baseActivity)) {
            net_tips.setVisibility(View.GONE);
        } else {
            net_tips.setVisibility(View.VISIBLE);
        }
        CoreApplication.getInstance().registerNetStateWatcher(this);
    }

    /**
     * 是否显示返回键 默认显示
     *
     * @return
     */
    public boolean isShowBackButton() {
        return true;
    }

    /**
     * @return 是否使用toolbar做为顶导
     */
    public abstract boolean isUseToolBar();

    @Override
    public void onNetStateChanged(boolean isNetConnect) {
        if (isNetConnect) {
            net_tips.setVisibility(View.GONE);
        } else {
            net_tips.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 不需要Toolbar的界面请返回false
     *
     * @return
     */
    public boolean isInitToolBar() {
        return true;
    }
}
